package com.sk.bilibili.utils;

import com.sk.bilibili.bean.Dynamic;
import com.sk.bilibili.bean.Praise;
import com.sk.bilibili.service.DynamicService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @author 邵康
 * @date 2021/12/20 11:12
 */
@Component
public class TransformUtils implements InitializingBean {

    @Autowired
    private DynamicService dynamicService;
    private Field type;
    private Field targetId;

    @Override
    public void afterPropertiesSet() throws Exception {
        Class<?> clazz = Dynamic.class;
        type = getField(clazz, "type");
        targetId = getField(clazz, "targetId");
    }

    @SneakyThrows
    private Field getField(Class<?> clazz, String fieldName) {
        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        return field;
    }

    @SneakyThrows
    public <T> T transform(T t) {
        Class<?> clazz = t.getClass();
        Field tType = getField(clazz, "type");
        Integer type = (Integer) tType.get(t);
        if (type == 8) {
            Field tTargetId = getField(clazz, "targetId");
            Integer targetId = (Integer) tTargetId.get(t);
            Dynamic dynamic = dynamicService.getById(targetId);
            tType.set(t, this.type.get(dynamic));
            tTargetId.set(t, this.targetId.get(dynamic));
        }
        return t;
    }


}
